﻿using Magicodes.WeiChat.Data.Models;
using Magicodes.WeiChat.Data.Models.Site;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Magicodes.WeiChat.Data.Migrations
{
    internal sealed class Configuration : DbMigrationsConfiguration<AppDbContext>
    {
        public Configuration()
        {
            ContextKey = "Magicodes.WeiChat.Models.ApplicationDbContext";
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = true;
            ////关闭自动生成迁移（让程序只打我们自己生成的迁移）
            //AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(AppDbContext context)
        {
            var tenant = context.Account_Tenants.FirstOrDefault(p => p.IsSystemTenant);
            if (tenant == null)
            {
                tenant = new Account_Tenant() { IsSystemTenant = true, Name = "系统租户", Remark = "系统租户，勿删！" };
                context.Account_Tenants.Add(tenant);
                context.SaveChanges();
            }

            #region 添加用户和角色
            //全局管理员多租户Id为1
            var store = new AppUserStore(context) { TenantId = tenant.Id };
            var userManager = new UserManager<AppUser, string>(store);
            var roleManager = new RoleManager<AppRole>(new AppRoleStore(context));
            var adminRole = new AppRole() { Id = "{74ABBD8D-ED32-4C3A-9B2A-EB134BFF5D91}", Name = "Admin", Description = "超级管理员，拥有最大权限" };
            if (!roleManager.RoleExists(adminRole.Name))
                roleManager.Create(adminRole);
            var user = new AppUser
            {
                Id = "{B0FBB2AC-3174-4E5A-B772-98CF776BD4B9}",
                UserName = "admin",
                Email = "liwq@magicodes.net",
                EmailConfirmed = true,
                TenantId = tenant.Id
            };
            if (!userManager.Users.Any(p => p.Id == user.Id))
            {
                var result = userManager.Create(user, "123456abcD");
                if (result.Succeeded)
                {
                    userManager.AddToRole(user.Id, adminRole.Name);
                }
            }
            #endregion

            #region 初始化菜单
            if (!context.Site_Menus.Any())
            {
                var menus = new List<Site_Menu>();
                var menu1 = MenuDataSeedHelper.CreateRootMenu(title: "菜单管理", action: "", controller: "", url: "", iconCls: "fa fa-th-large");
                menus.Add(menu1);
                menus.Add(MenuDataSeedHelper.CreateChildMenu(parentId: menu1.Id, title: "自定义菜单", action: "Index", controller: "Menus", url: "/Menus", iconCls: ""));

                var menu2 = MenuDataSeedHelper.CreateRootMenu(title: "粉丝管理", action: "", controller: "", url: "", iconCls: "fa fa-users");
                menus.Add(menu2);
                menus.Add(MenuDataSeedHelper.CreateChildMenu(parentId: menu2.Id, title: "粉丝管理", action: "Index", controller: "WeiChat_User", url: "/WeiChat_User", iconCls: ""));
                menus.Add(MenuDataSeedHelper.CreateChildMenu(parentId: menu2.Id, title: "用户组管理", action: "Index", controller: "WeiChat_UserGroup", url: "/WeiChat_UserGroup", iconCls: ""));

                var menu3 = MenuDataSeedHelper.CreateRootMenu(title: "素材管理", action: "", controller: "", url: "", iconCls: "fa fa-file-image-o");
                menus.Add(menu3);
                menus.Add(MenuDataSeedHelper.CreateChildMenu(parentId: menu3.Id, title: "图片管理", action: "Index", controller: "Site_Resources", url: "/Site_Resources?resourceType=0", iconCls: ""));
                menus.Add(MenuDataSeedHelper.CreateChildMenu(parentId: menu3.Id, title: "语音管理", action: "Index", controller: "Site_Resources", url: "/Site_Resources?resourceType=1", iconCls: ""));
                menus.Add(MenuDataSeedHelper.CreateChildMenu(parentId: menu3.Id, title: "视频管理", action: "Index", controller: "Site_Resources", url: "/Site_Resources?resourceType=2", iconCls: ""));
                menus.Add(MenuDataSeedHelper.CreateChildMenu(parentId: menu3.Id, title: "图文消息管理", action: "Index", controller: "Site_News", url: "/Site_News", iconCls: ""));
                menus.Add(MenuDataSeedHelper.CreateChildMenu(parentId: menu3.Id, title: "文章管理", action: "Index", controller: "Site_Article", url: "/Site_Article", iconCls: ""));

                var menu4 = MenuDataSeedHelper.CreateRootMenu(title: "消息管理", action: "", controller: "", url: "", iconCls: "fa  fa-comments-o");
                menus.Add(menu4);
                menus.Add(MenuDataSeedHelper.CreateChildMenu(parentId: menu4.Id, title: "文本推送", action: "Send", controller: "GroupMessage", url: "/GroupMessage/Send?type=0", iconCls: ""));
                menus.Add(MenuDataSeedHelper.CreateChildMenu(parentId: menu4.Id, title: "图片推送", action: "Send", controller: "GroupMessage", url: "/GroupMessage/Send?type=1", iconCls: ""));
                menus.Add(MenuDataSeedHelper.CreateChildMenu(parentId: menu4.Id, title: "语音推送", action: "Send", controller: "GroupMessage", url: "/GroupMessage/Send?type=3", iconCls: ""));
                menus.Add(MenuDataSeedHelper.CreateChildMenu(parentId: menu4.Id, title: "视频推送", action: "Send", controller: "GroupMessage", url: "/GroupMessage/Send?type=4", iconCls: ""));
                menus.Add(MenuDataSeedHelper.CreateChildMenu(parentId: menu4.Id, title: "图文推送", action: "Send", controller: "GroupMessage", url: "/GroupMessage/Send?type=5", iconCls: ""));
                menus.Add(MenuDataSeedHelper.CreateChildMenu(parentId: menu4.Id, title: "模板消息", action: "Index", controller: "WeiChat_MessagesTemplate", url: "/WeiChat_MessagesTemplate", iconCls: ""));

                var menu5 = MenuDataSeedHelper.CreateRootMenu(title: "场景二维码", action: "", controller: "", url: "", iconCls: "fa fa-qrcode");
                menus.Add(menu5);
                menus.Add(MenuDataSeedHelper.CreateChildMenu(parentId: menu5.Id, title: "二维码管理", action: "Index", controller: "WeiChat_QRCode", url: "/WeiChat_QRCode", iconCls: ""));

                var menu6 = MenuDataSeedHelper.CreateRootMenu(title: "客服管理", action: "", controller: "", url: "", iconCls: "fa fa-users");
                menus.Add(menu6);
                menus.Add(MenuDataSeedHelper.CreateChildMenu(parentId: menu6.Id, title: "客服管理", action: "Index", controller: "WeiChat_KFCInfo", url: "/WeiChat_KFCInfo", iconCls: ""));

                var menu7 = MenuDataSeedHelper.CreateRootMenu(title: "智能回复", action: "", controller: "", url: "", iconCls: "fa fa-slack");
                menus.Add(menu7);
                menus.Add(MenuDataSeedHelper.CreateChildMenu(parentId: menu7.Id, title: "关键字回复", action: "Index", controller: "WeiChat_KeyWordAutoReply", url: "/WeiChat_KeyWordAutoReply", iconCls: ""));
                menus.Add(MenuDataSeedHelper.CreateChildMenu(parentId: menu7.Id, title: "关注时回复", action: "Index", controller: "WeiChat_SubscribeReply", url: "/WeiChat_SubscribeReply", iconCls: ""));
                menus.Add(MenuDataSeedHelper.CreateChildMenu(parentId: menu7.Id, title: "答不上来配置", action: "Index", controller: "WeiChat_NotAnswerReply", url: "/WeiChat_NotAnswerReply", iconCls: ""));

                var menu8 = MenuDataSeedHelper.CreateRootMenu(title: "数据与统计", action: "", controller: "", url: "", iconCls: "fa fa-line-chart");
                menus.Add(menu8);
                menus.Add(MenuDataSeedHelper.CreateChildMenu(parentId: menu8.Id, title: "关键字回复统计", action: "Index", controller: "WeiChat_KeyWordReplyLog", url: "/WeiChat_KeyWordReplyLog", iconCls: ""));
                menus.Add(MenuDataSeedHelper.CreateChildMenu(parentId: menu8.Id, title: "位置统计", action: "Index", controller: "WeiChat_LocationEventLog", url: "/WeiChat_LocationEventLog", iconCls: ""));

                var menu9 = MenuDataSeedHelper.CreateRootMenu(title: "系统设置", action: "", controller: "", url: "", iconCls: "fa fa-cogs");
                menus.Add(menu9);
                menus.Add(MenuDataSeedHelper.CreateChildMenu(parentId: menu9.Id, title: "微信支付设置", action: "Index", controller: "WeiChat_PayConfig", url: "/WeiChat_PayConfig", iconCls: ""));

                context.Site_Menus.AddRange(menus);
                try
                {
                    context.SaveChanges();
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException ex)
                {
                    var str = "";
                    foreach (var item in ex.EntityValidationErrors)
                    {
                        foreach (var eitem in item.ValidationErrors)
                        {
                            str += eitem.PropertyName + ":" + eitem.ErrorMessage;
                        }
                    }
                    throw new Exception(str);
                }
                //初始化角色菜单
                if (!context.Role_Menus.Any(p => p.RoleId == adminRole.Id))
                {
                    foreach (var item in menus)
                    {
                        context.Role_Menus.Add(new Role_Menu()
                        {
                            MenuId = item.Id,
                            RoleId = adminRole.Id
                        });
                    }
                    context.SaveChanges();
                }
            }
            #endregion

            if (context.Site_Menus.Any(p => p.Tag == null))
            {
                var list = context.Site_Menus.Where(p => p.Tag == null);
                foreach (var item in list)
                {
                    item.Tag = "Tenant";
                }
                context.SaveChanges();
            }
        }
    }

    internal class MenuDataSeedHelper
    {
        static int orderNo = 0;
        public static Site_Menu CreateRootMenu(string title, string action, string controller, string url, string iconCls)
        {
            orderNo++;
            var id = Guid.NewGuid();
            return new Site_Menu()
            {
                Id = id,
                Title = title,
                Action = action,
                Controller = controller,
                Url = url,
                IconCls = iconCls,
                Path = id.ToString("N"),
                OrderNo = orderNo,
                Tag = "Tenant"
            };
        }

        public static Site_Menu CreateChildMenu(Guid parentId, string title, string action, string controller, string url, string iconCls)
        {
            orderNo++;
            var id = Guid.NewGuid();
            return new Site_Menu()
            {
                Id = id,
                ParentId = parentId,
                Title = title,
                Action = action,
                Controller = controller,
                Url = url,
                IconCls = iconCls,
                Path = string.Format("{0}-{1}", parentId.ToString("N"), id.ToString("N")),
                OrderNo = orderNo,
                Tag = "Tenant"
            };
        }
    }
}
